package com.logindemo.servlet; /**
 * @author wzm
 * @create 2023-03-07 11:11
 */

import com.logindemo.entity.User;
import com.logindemo.service.UserSerivce;
import com.logindemo.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserSerivce userSerivce = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受浏览器登录的请求 通过程序比对返回结果
        System.out.println("login");

        //1.设置编码  请求  响应
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //2.获取请求的参数 参数String
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //3.将参数封装为对象
        User user = new User(username,password);

        //4.调用Service执行登录的方法
        User login = userSerivce.login(user);

        //5.判断并跳转
        if(login == null){
            //登录失败
            response.getWriter().write("对不起，此用户不存在，登录失败！");
            return;
        }

        //成功进入首页
        request.getRequestDispatcher("/index.jsp").forward(request,response);


    }
}
